<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\RlAssemblyLocation;
use plugin\admin\app\model\RlGoods;
use plugin\admin\app\model\RlGoodsCate;
use plugin\admin\app\model\RlGoodsImage;
use plugin\admin\app\model\RlGoodsPeriodModel;
use plugin\admin\app\model\RlGoodsSpecificationModel;
use support\Db;
use support\facade\Logger;
use support\Request;
use support\Response;
use const support\CORRECT;
use const support\DENY;
use const support\identity_type_1;
use const support\identity_type_2;

/**
 * 研学产品管理 
 */
class RlGoodsController extends Base
{
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('rl-goods/index');
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     */
    public function select(Request $request): Response
    {
        $page = (int)$request->get('page');
        $limit = (int)$request->get('limit', 10);
        $goodsNum=RlGoods::where([
            'status'=>CORRECT
        ])->count();
        $goods=RlGoods::where([
            'status'=>CORRECT
        ])->offset(($page-1)*$limit)->limit($limit)->orderBy('sort','desc')->get()->toArray();
        //获取商品所涉及的分类ID组
        $cateIds=$goods?array_values(array_unique(array_column($goods,'goods_cate'))):[];
        $cateArr=RlGoodsCate::whereIn('id',$cateIds)->pluck('cate_title','id')->toArray();
        //获取集合地址ID组
        $assemblyIds=$goods?array_values(array_unique(array_column($goods,'assembly_location_id'))):[];
        $assemblyArr=RlAssemblyLocation::whereIn('id',$assemblyIds)->get()->toArray();
        $assemblyData=array_column($assemblyArr,'address_details','id');
        foreach ($goods as &$good){
            $good['goods_cate_title']=$cateArr[$good['goods_cate']]??'';
            $good['address_details']=$assemblyData[$good['assembly_location_id']]??'';
        }
        return json(['code' => 0, 'data' => $goods, 'count'=>$goodsNum,'msg' => '成功']);
    }

    /**
     * 查询单条数据
     * @param Request $request
     * @return Response
     */
    public function selectOne(Request $request): Response
    {
        $goodsId = (int)$request->post('goods_id',0);
        $goods=RlGoods::with('goodsImages')->where([
            'id'=>$goodsId
        ])->get()->toArray();
        foreach ($goods as &$good){
            $good['goods_labels']=str_replace('|',PHP_EOL,$good['goods_labels']);
            $good['goods_end_time']=$good['goods_end_time']?date('Y-m-d H:i:s',$good['goods_end_time']):'';
        }
        return json(['code' => 0, 'data' => $goods,'msg' => '成功']);
    }

    /**
     * 查询在架商品标题
     */
    public function selectGoodsTitles(): Response
    {
        $lists=RlGoods::where([
            'status'    =>CORRECT,
            'is_audit'  =>CORRECT,
            'is_upper'  =>CORRECT
        ])->select(['id','goods_title'])->get()->toArray();
        return $this->json(0,'成功',$lists);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            //获取商品信息
            $goods_sn=$request->post('goods_sn','');
            $goods_icon=$request->post('goods_icon','');
            $sort=$request->post('sort','');
            $goods_images=$request->post('goods_image',[]);
            $goods_image_sorts=$request->post('goods_image_sort',[]);
            $goods_title=$request->post('goods_title','');
            $goods_cate=$request->post('goods_cate','');
            $goods_sale_num=$request->post('goods_sale_num',0);
            $goods_stock_num=$request->post('goods_stock_num',0);
            $goods_appropriate_age=$request->post('goods_appropriate_age',0);
            $is_enroll_period=$request->post('is_enroll_period',2);
            $is_deadline=$request->post('is_deadline',2);
            $goods_end_time=$request->post('goods_end_time',0);
            $goods_details=$request->post('goods_details','');
            $is_allocation_mode=$request->post('is_allocation_mode',0);
            $allocation_rate=$request->post('allocation_rate',0)?:0;
            $allocation_amount=$request->post('allocation_amount',0)?:0;
            $is_repurchase_allocation_mode=$request->post('is_repurchase_allocation_mode',0);
            $repurchase_allocation_rate=$request->post('repurchase_allocation_rate',0)?:0;
            $repurchase_allocation_amount=$request->post('repurchase_allocation_amount',0)?:0;
            $assembly_location_id=$request->post('assembly_location_id',0);
            $goods_activity_cycle=$request->post('goods_activity_cycle','');
            $goods_recommend_reason=$request->post('goods_recommend_reason','');
            $location_province=$request->post('location_province','');
            $location_city=$request->post('location_city','');
            $location_area=$request->post('location_area','');
            $goods_labels=str_replace(PHP_EOL,'|',$request->post('goods_labels',''));

            $goodsData=[
                'goods_sn'=>$goods_sn,
                'goods_icon'=>$goods_icon,
                'goods_title'=>$goods_title,
                'goods_cate'=>$goods_cate,
                'goods_sale_num'=>$goods_sale_num,
                'goods_stock_num'=>$goods_stock_num,
                'goods_appropriate_age'=>$goods_appropriate_age,
                'is_enroll_period'=>$is_enroll_period,
                'is_deadline'=>$is_deadline,
                'goods_end_time'=>$goods_end_time?strtotime($goods_end_time):0,
                'goods_details'=>$goods_details,
                'create_time'=>time(),
                'is_allocation_mode'=>$is_allocation_mode,
                'allocation_rate'=>$allocation_rate,
                'allocation_amount'=>$allocation_amount,
                'is_repurchase_allocation_mode'=>$is_repurchase_allocation_mode,
                'repurchase_allocation_rate'=>$repurchase_allocation_rate,
                'repurchase_allocation_amount'=>$repurchase_allocation_amount,
                'assembly_location_id'=>$assembly_location_id,
                'goods_activity_cycle'=>$goods_activity_cycle,
                'goods_recommend_reason'=>$goods_recommend_reason,
                'location_province'=>$location_province,
                'location_city'=>$location_city,
                'location_area'=>$location_area,
                'goods_labels'=>$goods_labels,
                'sort'      =>$sort
            ];
            //将商品基本信息和商品图组保存
            DB::beginTransaction();
            try {
                //添加商品基本信息
                $goodsId=RlGoods::insertGetId($goodsData);
                if (!$goodsId){
                    DB::rollBack();
                    return $this->json(-1,'商品添加失败1');
                }
                //添加商品图片组信息
                $goodsImages=[];
                $keys=array_keys($goods_images);
                foreach ($keys as $key){
                    $goodsImages[]=[
                        'goods_id'=>$goodsId,
                        'goods_image'=>$goods_images[$key],
                        'sort'=>$goods_image_sorts[$key]??0,
                        'create_time'=>time()
                    ];
                }
                RlGoodsImage::insert($goodsImages);
                DB::commit();
            }catch (\Throwable $exception){
                DB::rollBack();
                Logger::app($exception);
                return $this->json(-1,'商品添加失败');
            }
            return $this->json(0,'成功');
        }
        return view('rl-goods/insert');
    }


    //更新状态
    public function updateStatus(Request $request): Response
    {
        $goods_id=$request->post('id',0);
        $ret=RlGoods::where('id',$goods_id)->update($request->post());
        if (!$ret){
            return $this->json(-1,'商品更新失败');
        }
        return $this->json(0,'成功');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            //获取商品信息
            $goods_id=$request->post('goods_id',0);
            $goods_sn=$request->post('goods_sn','');
            $goods_icon=$request->post('goods_icon','');
            $goods_images=$request->post('goods_image',[]);
            $goods_image_sorts=$request->post('goods_image_sort',[]);
            $goods_image_ids=$request->post('goods_image_id',[]);
            $goods_title=$request->post('goods_title','');
            $goods_cate=$request->post('goods_cate','');
            $goods_sale_num=$request->post('goods_sale_num',0);
//            $goods_stock_num=$request->post('goods_stock_num',0);
            $goods_appropriate_age=$request->post('goods_appropriate_age',0);
            $is_enroll_period=$request->post('is_enroll_period',2);
            $is_deadline=$request->post('is_deadline',2);
            $goods_end_time=$request->post('goods_end_time',0);
            $goods_details=$request->post('goods_details','');
            $is_allocation_mode=$request->post('is_allocation_mode',0);
            $allocation_rate=$request->post('allocation_rate',0)?:0;
            $allocation_amount=$request->post('allocation_amount',0)?:0;
            $is_repurchase_allocation_mode=$request->post('is_repurchase_allocation_mode',0);
            $repurchase_allocation_rate=$request->post('repurchase_allocation_rate',0)?:0;
            $repurchase_allocation_amount=$request->post('repurchase_allocation_amount',0)?:0;
            $assembly_location_id=$request->post('assembly_location_id',0);
            $goods_activity_cycle=$request->post('goods_activity_cycle','');
            $goods_recommend_reason=$request->post('goods_recommend_reason','');
            $location_province=$request->post('location_province','');
            $location_city=$request->post('location_city','');
            $location_area=$request->post('location_area','');
            $goods_labels=str_replace(PHP_EOL,'|',$request->post('goods_labels',''));
            $sort=$request->post('sort','');
            $goodsData=[
                'goods_sn'=>$goods_sn,
                'goods_icon'=>$goods_icon,
                'goods_title'=>$goods_title,
                'goods_cate'=>$goods_cate,
                'goods_sale_num'=>$goods_sale_num,
//                'goods_stock_num'=>$goods_stock_num,
                'goods_appropriate_age'=>$goods_appropriate_age,
                'is_enroll_period'=>$is_enroll_period,
                'is_deadline'=>$is_deadline,
                'goods_end_time'=>$goods_end_time?strtotime($goods_end_time):0,
                'goods_details'=>$goods_details,
                'is_allocation_mode'=>$is_allocation_mode,
                'allocation_rate'=>$allocation_rate,
                'allocation_amount'=>$allocation_amount,
                'is_repurchase_allocation_mode'=>$is_repurchase_allocation_mode,
                'repurchase_allocation_rate'=>$repurchase_allocation_rate,
                'repurchase_allocation_amount'=>$repurchase_allocation_amount,
                'assembly_location_id'=>$assembly_location_id,
                'goods_activity_cycle'=>$goods_activity_cycle,
                'goods_recommend_reason'=>$goods_recommend_reason,
                'location_province'=>$location_province,
                'location_city'=>$location_city,
                'location_area'=>$location_area,
                'goods_labels'=>$goods_labels,
                'update_time'=>time(),
                'sort'=>$sort
            ];
            //将商品基本信息和商品图组保存
            DB::beginTransaction();
            try {
                //添加商品基本信息
                $ret=RlGoods::where('id',$goods_id)->update($goodsData);
                if (!$ret){
                    DB::rollBack();
                    return $this->json(-1,'商品添加失败1');
                }
                //添加商品图片组信息
                $keys=array_keys($goods_images);
                foreach ($keys as $key){
                    $id=$goods_image_ids[$key];
                    if ($id){
                        $goodsImages=[
                            'goods_id'=>$goods_id,
                            'goods_image'=>$goods_images[$key],
                            'sort'=>$goods_image_sorts[$key]??0,
                            'update_time'=>time()
                        ];
                        $ret=RlGoodsImage::where('id',$id)->update($goodsImages);
                    }else{
                        $goodsImages=[
                            'goods_id'=>$goods_id,
                            'goods_image'=>$goods_images[$key],
                            'sort'=>$goods_image_sorts[$key]??0,
                            'create_time'=>time()
                        ];
                        $ret=RlGoodsImage::insert($goodsImages);
                    }
                    if (!$ret){
                        DB::rollBack();
                        return $this->json(-1,'商品轮播图组更新失败');
                    }
                }
                DB::commit();
            }catch (\Throwable $exception){
                DB::rollBack();
                Logger::app($exception);
                var_dump($exception->getMessage());
                return $this->json(-1,'商品更新失败');
            }
            return $this->json(0,'成功');
        }
        return view('rl-goods/update');
    }

    //规格列表
    public function specification(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $goodsId=$request->post('goods_id',0);
            $data=[];
            $goodsSpecification=RlGoodsSpecificationModel::where([
                'goods_id'=>$goodsId
            ])->where('type',identity_type_1)->select(['type','goods_original_price','goods_sale_price','status'])->first();
            if (empty($goodsSpecification->type)){
                $data[]=[
                    'type'=>identity_type_1,
                    'goods_original_price'=>'',
                    'goods_sale_price'=>'',
                    'status'=>1
                ];
            }else{
                $data[]=$goodsSpecification->toArray();
            }
            $goodsSpecification=RlGoodsSpecificationModel::where([
                'goods_id'=>$goodsId
            ])->where('type',identity_type_2)->select(['type','goods_original_price','goods_sale_price','status'])->first();
            if (empty($goodsSpecification->type)){
                $data[]=[
                    'type'=>identity_type_2,
                    'goods_original_price'=>'',
                    'goods_sale_price'=>'',
                    'status'=>1
                ];
            }else{
                $data[]=$goodsSpecification->toArray();
            }
            return $this->json(0,'成功',$data);
        }
        return view('rl-goods/insert-specification');
    }

    public function updateSpecification(Request $request): Response
    {
        $columns=$request->post('columns',[]);
        $goodsId=$request->post('goods_id',0);
        foreach ($columns as $column){
            RlGoodsSpecificationModel::updateOrInsert([
                'type'      =>$column['type'],
                'goods_id'  =>$goodsId
            ],[
                'goods_original_price'=>$column['goods_original_price'],
                'goods_sale_price'=>$column['goods_sale_price'],
                'status'=>$column['status']
            ]);
        }
        return $this->json(0,'成功');
    }

    public function period(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $goodsId=$request->post('goods_id',0);
            $data=RlGoodsPeriodModel::where([
                'goods_id'  =>$goodsId,
                'status'=>CORRECT
            ])->select([
                'id','goods_period_title','goods_period_date','goods_sale_num','goods_stock_num','status','min_group_num'
            ])->get()->toArray();
            foreach ($data as &$datum){
                $datum['goods_period_date']=date('Y-m-d',$datum['goods_period_date']);
            }
            return $this->json(0,'成功',$data);
        }
        return view('rl-goods/insert-period');
    }

    public function updatePeriod(Request $request): Response
    {
        $columns=$request->post('columns',[]);
        $goodsId=$request->post('goods_id',0);
        $datePattern = '/^\d{4}-\d{2}-\d{2}$/';
        //对整体日期格式进行正则校验
        $goods_period_dates=array_column($columns,'goods_period_date');
        foreach ($goods_period_dates as $k=>$goods_period_date){
            if (!preg_match($datePattern, $goods_period_date)) {
                return $this->json(-1,'日期格式有误，请修改后重新提交');
            }
            $columns[$k]['goods_period_date']=strtotime($goods_period_date);
        }
        DB::beginTransaction();
        try {
            //计算总库存
            $totalGoodsStockNum=0;
            //计算商品总销量
            $totalGoodsSaleNum=0;
            foreach ($columns as $column){
                if ($column['id']){
                    $re=RlGoodsPeriodModel::where('id',$column['id'])->update([
                        'goods_period_date'=>$column['goods_period_date'],
                        'goods_period_title'=>$column['goods_period_title'],
                        'goods_sale_num'=>$column['goods_sale_num'],
                        'goods_stock_num'=>$column['goods_stock_num'],
                        'min_group_num'=>$column['min_group_num'],
                        'status'=>$column['status'],
                        'goods_id'  =>$goodsId,
                        'update_time'=>time()
                    ]);
                }else{
                    $re=RlGoodsPeriodModel::insertGetId([
                        'goods_period_date'=>$column['goods_period_date'],
                        'goods_period_title'=>$column['goods_period_title'],
                        'goods_sale_num'=>$column['goods_sale_num'],
                        'goods_stock_num'=>$column['goods_stock_num'],
                        'min_group_num'=>$column['min_group_num'],
                        'status'=>$column['status'],
                        'goods_id'  =>$goodsId,
                        'create_time'=>time()
                    ]);
                }
                if (!$re){
                    DB::rollBack();
                    return $this->json(-1,'营期操作失败'.$column['id']);
                }
                $totalGoodsStockNum+=$column['goods_stock_num'];
                $totalGoodsSaleNum+=$column['goods_sale_num'];
            }
            //更新商品信息
            $ret=RlGoods::where('id',$goodsId)->update([
                'goods_sale_num'=>$totalGoodsSaleNum,
                'goods_stock_num'=>$totalGoodsStockNum
            ]);
            if (!$ret){
                DB::rollBack();
                return $this->json(-1,'更新商品信息失败'.$goodsId);
            }
            DB::commit();
        }catch (\Throwable $exception){
            DB::rollBack();
            Logger::app($exception);
            return $this->json(-1,'营期添加失败');
        }
        return $this->json(0,'成功');
    }

    public function location(): Response
    {
        $data=RlAssemblyLocation::where([
            'status'=>CORRECT
        ])->get()->toArray();
        return $this->json(0,'成功',$data);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $id=$request->post('id','');
        $ret=  RlGoods::where('id',$id)->update([
            'status'=>2
        ]);
        if (!$ret){
            return $this->fail('删除协议失败');
        }
        return $this->success('删除协议成功');
    }

}
